import {
  defineStore
} from 'pinia'

export const useSpeciesStore = defineStore('species', {
  // 状态定义
  state: () => ({
    currentSpecies: null,
    favorites: [],
    cache: {},
    error: null,
    loading: false
  }),

  // 计算属性
  getters: {
    isFavorite: (state) => (id) => {
      return state.favorites.includes(id)
    },
    legalNotice: (state) => {
      return state.currentSpecies?.legal || {}
    }
  },

  // 方法定义
  actions: {
    async fetchSpeciesDetail(speciesId) {
      try {
        this.loading = true

        // 检查缓存
        if (this.cache[speciesId]) {
          this.currentSpecies = this.cache[speciesId]
          return
        }

        // 调用云函数
        const res = await uniCloud.callFunction({
          name: 'getSpeciesDetail',
          data: {
            speciesId
          }
        })

        if (res.result.code === 200) {
          this.currentSpecies = res.result.data
          this.cache[speciesId] = res.result.data
        } else {
          throw new Error(res.result.message || '数据获取失败')
        }
      } catch (err) {
        this.error = err.message
        console.error('物种详情加载失败:', err)
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    toggleFavorite(speciesId) {
      const index = this.favorites.indexOf(speciesId)
      if (index > -1) {
        this.favorites.splice(index, 1)
      } else {
        this.favorites.push(speciesId)
      }
      uni.setStorageSync('species_favorites', this.favorites)
    },

    async fetchLegalInfo(speciesId) {
      return uniCloud.callFunction({
        name: 'getLegalInfo',
        data: {
          speciesId
        }
      })
    },

    initStore() {
      const stored = uni.getStorageSync('species_favorites')
      if (stored) this.favorites = stored
    }
  },

  // 持久化配置
  persist: {
    key: 'species_store',
    paths: ['favorites'],
    storage: {
      getItem: (key) => uni.getStorageSync(key),
      setItem: (key, value) => uni.setStorageSync(key, value)
    }
  }
})